package com.jww.controller;

import com.jww.domain.User;
import com.jww.service.UserService;
import com.jww.service.impl.UserServletImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserServlet extends HttpServlet {

    private UserService service = new UserServletImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  设置请求和响应编码
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用登录方法
        User user = service.login(username, password);
        //进行判断
        if (user != null) {
            //将用户名存入会话中
            req.getSession().setAttribute("username", username);
            //校验正确正确后返回true
            resp.getWriter().write("true");
        } else {
            resp.getWriter().write("false");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
